namespace RBAC.Read.Api.Application.Handler.QualityHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.QualityManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.QualityCommand;
    using System;
    using System.Linq;
    using System.IO;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;

    /// <summary>
    /// 质量工单导出处理器（导出为 .xlsx 字节流）。
    /// </summary>
    public class ExportQualityOrderHandler : IRequestHandler<ExportQualityOrderCommand, APIResult<byte[]>>
    {
        private readonly IBaseRepository<QualityOrder> _orderRepo;
        private readonly ILogger<ExportQualityOrderHandler> _logger;

        public ExportQualityOrderHandler(IBaseRepository<QualityOrder> orderRepo, ILogger<ExportQualityOrderHandler> logger)
        {
            _orderRepo = orderRepo;
            _logger = logger;
        }

        public Task<APIResult<byte[]>> Handle(ExportQualityOrderCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<byte[]>();
            try
            {
                // 取消检查
                cancellationToken.ThrowIfCancellationRequested();

                // 使用仓储分页，与列表接口保持一致
                var (items, total) = _orderRepo.GetPaged(
                    request.PageIndex <= 0 ? 1 : request.PageIndex,
                    request.PageSize <= 0 ? 10 : request.PageSize,
                    "IsDeleted = 0",
                    request.OrderBy,
                    null);

                // 使用 NPOI 生成 .xlsx
                IWorkbook wb = new XSSFWorkbook();
                var sheet = wb.CreateSheet("质量工单");

                // 样式：表头加粗、居中
                var headerStyle = wb.CreateCellStyle();
                headerStyle.Alignment = HorizontalAlignment.Center;
                var fontBold = wb.CreateFont();
                fontBold.IsBold = true;
                headerStyle.SetFont(fontBold);

                // 样式：日期格式
                var dateStyle = wb.CreateCellStyle();
                var dataFormat = wb.CreateDataFormat();
                dateStyle.DataFormat = dataFormat.GetFormat("yyyy-mm-dd hh:mm:ss");

                // 表头：优化字段顺序与命名
                string[] headers = new[]
                {
                    "序号","工单编号","主题","来源工单","产品名称",
                    "负责人","工序数量","报工次数","状态","备注","创建时间"
                };
                var header = sheet.CreateRow(0);
                for (int i = 0; i < headers.Length; i++)
                {
                    var cell = header.CreateCell(i);
                    cell.SetCellValue(headers[i]);
                    cell.CellStyle = headerStyle;
                }

                // 数据行
                for (int i = 0; i < items.Count; i++)
                {
                    var x = items[i];
                    var row = sheet.CreateRow(i + 1);
                    int c = 0;
                    row.CreateCell(c++).SetCellValue(i + 1); // 序号
                    row.CreateCell(c++).SetCellValue(x.OrderNo ?? string.Empty);
                    row.CreateCell(c++).SetCellValue(x.Title ?? string.Empty);
                    row.CreateCell(c++).SetCellValue(x.SourceWorkOrderNo ?? string.Empty);
                    row.CreateCell(c++).SetCellValue(x.ProductName ?? string.Empty);
                    row.CreateCell(c++).SetCellValue(x.OwnerUserName ?? string.Empty);
                    if (x.ProcessCount.HasValue) row.CreateCell(c++).SetCellValue((double)x.ProcessCount.Value); else row.CreateCell(c++).SetCellValue(string.Empty);
                    if (x.ReportCount.HasValue) row.CreateCell(c++).SetCellValue((double)x.ReportCount.Value); else row.CreateCell(c++).SetCellValue(string.Empty);
                    // 状态转义显示
                    string statusText = x.Status switch { 0 => "未完成", 1 => "已完成", 2 => "已取消", _ => x.Status.ToString() };
                    row.CreateCell(c++).SetCellValue(statusText);
                    row.CreateCell(c++).SetCellValue(x.Remark ?? string.Empty);
                    var ctCell = row.CreateCell(c++);
                    ctCell.SetCellValue(x.CreateTime);
                    ctCell.CellStyle = dateStyle;
                }

                // 自适应列宽（限制最大宽度）
                for (int i = 0; i < headers.Length; i++)
                {
                    sheet.AutoSizeColumn(i);
                    var width = sheet.GetColumnWidth(i);
                    sheet.SetColumnWidth(i, Math.Min(width + 512, 100 * 256)); // 最多 ~100 字符
                }

                // 写入内存流
                using var ms = new MemoryStream();
                wb.Write(ms, leaveOpen: true);
                result.Code = APIEnums.Success;
                result.Msg = "导出成功";
                result.Data = ms.ToArray();
            }
            catch (OperationCanceledException)
            {
                _logger.LogWarning("质量工单导出被取消");
                result.Code = APIEnums.Error;
                result.Msg = "请求已取消";
                result.Data = Array.Empty<byte>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "质量工单导出失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "导出失败";
                result.Data = Array.Empty<byte>();
            }

            return Task.FromResult(result);
        }
    }
}
